package com.jason.digest.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileDigestUtils {

    /**
     * MD5 加密长度: 32字节数量
     */
    private static final String MD5 = "MD5";

    /**
     * SHA-1 加密长度: 40字节数量
     */
    private static final String SHA1 = "SHA-1";

    /**
     * SHA-256 加密长度: 64字节数量
     */
    private static final String SHA256 = "SHA-256";

    /**
     * SHA-512 加密长度: 128字节数量
     */
    private static final String SHA512 = "SHA-512";

    /**
     * 消息摘要算法，是单向且不可逆的
     *
     * @param path  消息类型
     * @param algorithm 算法类型
     * @return
     */
    public static String encryptDigest(String path,String algorithm){

        try {
            FileInputStream fis = new FileInputStream(new File(path));

            int len = 0;
            byte[] buff = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            while((len=fis.read(buff)) != -1){
                baos.write(buff, 0, len);
            }

            //获取消息摘要对象
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            //消息摘要(数字摘要)
            byte[] digest = messageDigest.digest(baos.toByteArray());
            return toHex(digest);
        } catch (NoSuchAlgorithmException e) {
            System.out.println("加密失败");
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String toHex(byte[] digest){
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            //转成16进制
            String s = Integer.toHexString(b & 0xff);
            if(s.length() == 1){
                // 如果生成的字符只有一个，前面补0
                sb.append("0");
            }
            sb.append(s);
        }
        return sb.toString();
    }
}
